<!-- 期末结账 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <!-- <a-col :class="!editMask?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="!editMask?handlerSubmit():''">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">确认</div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div :class="currentId?'':'btns-disable'">
                                <div class="btns" @click="currentId?handleRemove(1):''">
                                    <a-icon class="btns-icon" type="stop" />
                                    <div class="btns-text">结账</div>
                                </div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div :class="currentId?'':'btns-disable'">
                                <div class="btns" @click="currentId?handleRemove(0):''">
                                    <a-icon class="btns-icon" type="issues-close" />
                                    <div class="btns-text">恢复</div>
                                </div>
                            </div>
                        </a-col> -->
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="syncFun">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div ref="print" class="credentials-wrapper">
                <h3 class="text-center">
                    <span class="text-name">{{pageTitle}}</span><br>
                </h3>
                <section style="position:relative">
                    <a-row>
                        <a-col :span="10" :push="6">
                            <div style="font-weight:bold">年份: {{moment().format('YYYY')}}</div>
                            <div class="table-box margin-top-10">
                                <a-table id="credentials_tb" class="atable-edit" :columns="columns" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered>
                                    <template slot="inTerminalState" slot-scope="text,record,index">
                                        <div v-if="record.currentPeriod == 1">
                                            <a-switch :disabled="bigStatusMonth > record.currentPeriod" checked-children="已结账" un-checked-children="未结账" :checked="text" @change="changeState(text, record)" />
                                        </div>
                                        <div v-else-if="dataSource[index-1].inTerminalState == 1">
                                            <a-switch :disabled="bigStatusMonth > record.currentPeriod" checked-children="已结账" un-checked-children="未结账" :checked="text" @change="changeState(text, record)" />
                                        </div>
                                    </template>
                                </a-table>
                            </div>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="10" :push="6">
                            <div class="margin-top-10" style="border:1px solid #ccc;padding:5px;">
                                <!-- <div style="text-align:center">
                                    <a-button :type="bigStatusMonth == 12 ?'primary':''" @click="settleYearClick">结转下年</a-button>
                                </div> -->
                                <div style="font-weight:bold" v-if="bigStatusMonth==0">待结账月份：{{bigStatusYear}}年1月<br></div>
                                <div style="font-weight:bold" v-else-if="bigStatusMonth<=11 && bigStatusMonth>0">待结账月份：{{bigStatusYear}}年{{bigStatusMonth + 1}}月<br></div>
                                注：<br>
                                (1) 期末结账顺序：业务结账->财务结账<br>
                                (2) 已经结账的月份不能再填制非调整凭证。<br>
                                (3) 还有未记账凭证的月份不能结账。<br>
                                (4) 每月对账正确后才能结账。<br>
                                (5) 年底结账时先进行数据备份后再结账。<br>
                            </div>
                        </a-col>
                    </a-row>
                </section>
            </div>

        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <div v-html="stylePrint"></div>
    </div>
</template>
<script>


import editableCell from "../accounting/editTable/EditableCell";

// import { save, examine, remove, getList, getPage, getCode, book } from '@/api/finance/credentials';
import { save, getList, remove } from '@/api/finance/subjectsBalance';

import { list as listAccount } from "@/api/erp/account";
import { endSettle, settleYear,postSettleSave} from "@/api/erp/period";//期末结账

import { pageList as categoryList } from "@/api/erp/category";
import searchGroupHeader from "@/components/PopUpLayer/searchGroupHeader";
import FormSearchGroup from '@/components/Form/FormSearchGroup';
import moment from "moment";
import { getCurrencyDetailId } from "@/api/erp/currency";

export default {
    components: {
        editableCell,
        searchGroupHeader,
        FormSearchGroup,
    },
    data () {
        return {
            //----------↓样式----------
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            formLayout: "inline",
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 8
            },
            editMask: true,
            //----------↑样式----------
            pageTitle: this.$route.meta.name,
            pagination: {
                current: 1,
                pageSize: 20,
                total: 0,
                size: 'small',
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={20}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.getDataList();
                }
            },
            customClick: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        this.openMenu(e);
                        console.log('右键点击的', index);
                        this.thisClickId = index;
                    },
                    click: () => {
                        this.currentIndexTable = index;
                        console.log('当前点击的行下标', this.currentIndexTable)
                    }
                },
            }),
            customClickList: (record, index) => ({
                on: {
                    click: () => {
                        this.showModel = 'order';
                        this.dataSource = [];

                        //外币核算
                        let array = [];
                        let wb = [record.currencyBeginAmount, record.currencyName];
                        let wbFilter = wb.filter(r => {
                            return r;
                        })
                        array.unshift(wbFilter.join(','))

                        //外币数量|| 数量
                        let sl = [this.quantityBegin];
                        let slFilter = sl.filter(r => {
                            return r;
                        })
                        array.unshift(slFilter.join(','))


                        let b = array.filter(r => {
                            return r && r.trim();
                        })

                        record.auxiliaryItem = b.join('/');
                        console.log(record);

                        this.dataSource[0] = record;
                        this.currentId = record.id;

                        this.editMask = false;
                        this.reload();
                        // this.getDataNewPage(5);
                    }
                }
            }),
            searchText: null,
            thisClickId: null,

            columns: [{
                title: '会计月份',
                dataIndex: 'date',
                width: 50,
                ellipsis: true,
                customRender: (text, record, index) => {
                    return index + 1 + '月';
                },
                align: 'center',
            }, {
                title: '起始日期',
                dataIndex: 'beginDate',
                width: 150,
                align: 'center',
                ellipsis: true,
            }, {
                title: '结束日期',
                dataIndex: 'endDate',
                width: 150,
                align: 'center',
                ellipsis: true,
            }, {
                title: '是否结账',
                dataIndex: 'inTerminalState',
                width: 150,
                align: 'center',
                ellipsis: true,
                scopedSlots: { customRender: "inTerminalState" }
            }],
            dataSource: [],
            visible: false,
            top: 0,
            left: 0,
            editColumnArraya: [],
            isRouterAlive: true,
            dataJson: {
                // code: null,
                // classWord: null,//凭证字
                // vclassName: null,
                // vclassId: null,
                // businessDate: moment().format('YYYY-MM-DD'),
                // attachedData: null,
                // contractNo: null,
            },
            auxiliaryModal: false,//辅助计量弹窗是否显示
            voucherState: 0,    //审核状态
            invalidState: 0,    //作废状态
            voucherCode: 0,     //凭证编码  

            // settleName: null,   //结算方式
            // settleId: null,     //结算方式id
            // bankAccount: null,   //银行账号
            // bankId: null,        //银行id
            // bankName: null,      //银行名称
            // officeName: null,
            // officeId: null,
            // userName: null,
            // userId: null,
            // crmName: null,
            // crmId: null,
            // vendorName: null,
            // vendorId: null,
            // projectName: null,
            // projectId: null,
            // billDate: moment().format('YYYY-MM-DD'),         //票据日期
            // billNo: null,           //票据号
            currencyBeginAmount: null,   //原币金额
            currencyId: null,       //币种id
            currencyName: null,     //币种名称
            exchangeRate: null,     //汇率
            debitAmountType: 1,     //借贷方向
            quantityBegin: null,         //数量
            price: null,            //单价
            unitId: null,           //计量单位id
            unitName: null,         //计量单位名称

            isBank: false,   //是否现金，银行，等价物
            isAuxaccCustomer: false,    //是否客户核算
            isAuxaccDepartment: false,  //是否部门核算
            isAuxaccPerson: false,      //是否个人核算
            isAuxaccProject: false,     //是否项目核算
            isAuxaccSupplier: false,    //是否供应商核算
            isExchange: false,           //是否外币核算
            isQuantity: false,           //是否数量核算

            currentIndexTable: null,     //当前点击的行下标

            totalDebitAmount: null,  //借方金额合计
            totalCreditAmount: null,      //贷方金额合计

            currentId: null,     //当前凭证id
            currentCategoryArray: [],//当前凭证数组
            currentTitle: '凭证',
            calDirection: 1, //折算方式 1:原币*汇率=本位币 2:原币/汇率=本位币
            listDataSource: [],
            bigStatusMonth: 0,//当前结账月份最大月份
            bigStatusYear: new Date().getFullYear(),//当前结账最大年份
        };
    },
    created () {
        this.editColumnArray(this.columns);
        this.ListAccount();

        // this.dataSource = [];
        // let year = new Date().getFullYear();
        // let month = new Date().getMonth() + 1;
        // console.log(year, month)
        // for (let i = 0; i < 12; i++) {
        //     let array = { "date": `${year}年${i + 1}月` }
        //     this.dataSource.push(array);
        // }
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    methods: {
        moment,
        // 获取 账套信息
        ListAccount () {
            const { accountMap, year } = this;
            listAccount().then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.dataSource = data[0].erpPeriodList;
                    console.log(response)



                    //最大结账日期


                    this.dataSource.forEach(item => {
                        if (item.inTerminalState == 1) {
                            this.bigStatusMonth = item.currentPeriod;//最大结账的月份
                            this.bigStatusYear = item.currentYear;
                        }
                    });
                    // let yearDataChildren = [];
                    // data.forEach(item => {
                    //     accountMap.set(item.accountYear, item);
                    //     yearDataChildren.push({
                    //         title: item.accountYear + "",
                    //         key: item.accountYear + ""
                    //     });
                    // })
                    // this.$set(this.yearData[0], "children", yearDataChildren);
                    // this.selectedYearKeys = [this.year + ""];
                    // this.currentAccount = accountMap.get(year * 1) || {};
                    // this.erpPeriodList = this.currentAccount.erpPeriodList || [];
                }
            }).catch(error => { });
        },
        changeState (e, record) {
            //-gw
            console.log(e, record);
            let requestData = {
                beginDate: record.beginDate,
                endDate: record.endDate,
                status: e ? 0 : 1
            };
            if (requestData.status == 0) {
                if (record.currentPeriod != this.bigStatusMonth) {
                    this.$message.warning('只能按序取消结账!');
                    return false;
                }
            }
            postSettleSave(requestData).then(res => {
                if (res.code === 200) {
                    if (requestData.status == 1) {
                        this.$message.success(`${record.currentPeriod}月,结账成功`);
                    } else {
                        this.$message.success(`${record.currentPeriod}月,取消结账成功`);
                        this.bigStatusMonth = record.currentPeriod - 1;
                    }
                    this.ListAccount();
                }
            })
        },
        settleYearClick () {
            if (this.bigStatusMonth < 12) {
                this.$message.warning('本年度必须全部结账才能结转下年');
                return;
            }
            settleYear().then(res => {
                if (res.code === 200) {
                    this.$message.success('结转下年成功');
                }
            })
        },
        newPage () {
            this.showModel = 'order';
            this.editMask = false;
            this.voucherState = 0;
            this.invalidState = 0;
            this.dataJson = {
                vclassName: null,
                vclassId: null,
                // businessDate: moment().format('YYYY-MM-DD'),
            };

            this.dataSource = [];
            for (let i = 0; i < 10; i++) {
                let array = {}
                this.dataSource.push(array);
            }
            this.reload();
            this.clearTipsData();
        },
        onChangeBusinessDate (e, v) {
            //业务时间改变
            this.dataJson.businessDate = v;
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        onCellChange (indexTable, dataIndex, value) {
            console.log('进入了---------第一次选择科目时的弹窗');
            //当前点击的行下标
            this.currentIndexTable = indexTable;
            console.log('当前点击的数据：', value);

            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            if (dataIndex == 'accountingName') {
                if (value) {
                    target['accountingName'] = value.treeNames.split('/').join('-');
                    target['accountingId'] = value.id;
                    target['accountingCode'] = value.code;

                    value.isAuxaccCustomer ? target['crmId'] = 0 : target['crmId'] = null;//客户
                    value.isAuxaccDepartment ? target['officeId'] = 0 : target['officeId'] = null;//部门
                    value.isAuxaccPerson ? target['userId'] = 0 : target['userId'] = null;//个人
                    value.isAuxaccProject ? target['projectId'] = 0 : target['projectId'] = null;//项目
                    value.isAuxaccSupplier ? target['vendorId'] = 0 : target['vendorId'] = null;//供应商
                    value.isBank || value.isCash || value.isCashEquivalents ? target['settleId'] = 0 : target['settleId'] = null;//现金银行
                    value.isQuantity ? target['unitId'] = value.unitId : target['unitId'] = null;   //是否数量核算
                    value.isExchange ? target['currencyId'] = value.defaultCurrencyId : target['currencyId'] = null;//是否外币核算

                    target['unitId'] = value.unitId;            //计量单位id
                    target['unitName'] = value.unitName;        //计量单位名称
                    target['currencyId'] = value.defaultCurrencyId;            //币种id
                    target['currencyName'] = value.defaultCurrencyName;        //币种名称

                    if (value.isAuxaccCustomer || value.isAuxaccDepartment || value.isAuxaccPerson || value.isAuxaccProject || value.isAuxaccSupplier || value.isBank || value.isCash || value.isCashEquivalents || value.isQuantity || value.isExchange) {
                        this.clearTipsData();

                        this.isBank = (value.isBank || value.isCash || value.isCashEquivalents) ? true : false;
                        this.isAuxaccCustomer = value.isAuxaccCustomer;
                        this.isAuxaccDepartment = value.isAuxaccDepartment;
                        this.isAuxaccPerson = value.isAuxaccPerson;
                        this.isAuxaccProject = value.isAuxaccProject;
                        this.isAuxaccSupplier = value.isAuxaccSupplier;
                        this.isExchange = value.isExchange;
                        this.isQuantity = value.isQuantity;

                        this.currencyBeginAmount = value.currencyBeginAmount;   //原币金额
                        this.currencyId = value.defaultCurrencyId;       //币种id
                        this.currencyName = value.defaultCurrencyName; //币种名称
                        this.exchangeRate = value.exchangeRate;    //汇率
                        // this.debitAmountType = value.debitAmount > 0 ? 1 : 2;     //借贷方向
                        this.quantityBegin = value.quantityBegin;        //数量
                        this.price = value.price;           //单价
                        this.unitId = value.unitId;          //计量单位id
                        this.unitName = value.unitName;        //计量单位名称

                        this.auxiliaryModal = true;//显示弹窗
                    }
                } else {
                    target['accountingName'] = null;
                    target['accountingId'] = null;
                }


            } else if (dataIndex == 'debitAmount') {
                //借方金额
                // let reg = /^[0-9][0-9]*(\.[0-9]{1,2})?$/;
                // if(!reg.test(value)){
                //     alert(1)
                //     target[dataIndex] = null;
                //     return
                // }

                target[dataIndex] = value;
                if (value) {
                    target['creditAmount'] = null;
                }
            } else if (dataIndex == 'creditAmount') {
                //贷方金额

                // let reg = /^[0-9][0-9]*(\.[0-9]{1,2})?$/;
                // if(!reg.test(value)){
                //     alert(2)
                //     target[dataIndex] = null;
                //     return
                // }

                target[dataIndex] = value;
                if (value) {
                    target['debitAmount'] = null;
                }
            } else {
                target[dataIndex] = value;
            }

            this.$nextTick(() => {
                this.dataSource = dataSource;
                this.reload();
            })


        },
        getCurrencyDetailId (id) {
            getCurrencyDetailId({ id: id }).then(res => {
                if (res.code === 200) {
                    this.calDirection = res.data.calDirection;
                }
            })
        },
        clearTipsData () {
            //清空数据
            this.currentId = null;

            this.settleName = null;
            this.settleId = null;
            // this.bankAccount = null;   //银行账号
            // this.bankId = null;        //银行id
            // this.bankName = null;      //银行名称
            // this.officeName = null;
            // this.officeId = null;
            // this.userName = null;
            // this.userId = null;
            // this.crmName = null;
            // this.crmId = null;
            // this.projectName = null;
            // this.projectId = null;
            // this.billDate = moment().format('YYYY-MM-DD');
            // this.billNo = null;

            this.currencyBeginAmount = null;   //原币金额
            this.currencyId = null;       //币种id
            this.currencyName = null;    //币种名称
            this.exchangeRate = null;    //汇率
            this.debitAmountType = 1;     //借贷方向
            this.quantityBegin = null;        //数量
            this.price = null;           //单价
            this.unitId = null;          //计量单位id
            this.unitName = null;        //计量
        },
        ok () {
            this.dataSource.forEach((item, index) => {
                if (index == this.currentIndexTable) {
                    //判断弹窗必填
                    // if (this.isBank) {//现金银行
                    //     if (!this.settleId || !this.billDate || !this.billNo) {
                    //         this.$message.warning('现金银行信息必须填写完整');
                    //         return;
                    //     }
                    // }
                    // if (this.isAuxaccDepartment) {//部门
                    //     if (!this.officeId) {
                    //         this.$message.warning('部门必须选择');
                    //         return;
                    //     }
                    // }
                    // if (this.isAuxaccCustomer) {//客户往来
                    //     if (!this.crmId) {
                    //         this.$message.warning('客户必须选择');
                    //         return;
                    //     }
                    // }
                    // if (this.isAuxaccPerson) {//个人
                    //     if (!this.userId) {
                    //         this.$message.warning('个人必须选择');
                    //         return;
                    //     }
                    // }
                    // if (this.isAuxaccSupplier) {//供应商往来
                    //     if (!this.vendorId) {
                    //         this.$message.warning('项目必须选择');
                    //         return;
                    //     }
                    // }
                    // if (this.isAuxaccProject) {//项目
                    //     if (!this.projectId) {
                    //         this.$message.warning('项目必须选择');
                    //         return;
                    //     }
                    // }

                    if (this.isExchange) {//外币核算
                        if (!this.currencyBeginAmount) {
                            this.$message.warning('请输入外币期初金额');
                            return;
                        }
                        // if (!this.exchangeRate) {
                        //     this.$message.warning('请选择汇率');
                        //     return;
                        // }
                    }

                    if (this.isQuantity) {//数量核算
                        if (!this.quantityBegin) {
                            this.$message.warning('请输入数量');
                            return;
                        }
                        // if (!this.price) {
                        //     this.$message.warning('请输入单价');
                        //     return;
                        // }
                    }

                    // if (this.isQuantity && this.isExchange) {//外币数量核算
                    //     if (!this.quantityBegin) {
                    //         this.$message.warning('请输入数量');
                    //         return;
                    //     }
                    //     if (!this.price) {
                    //         this.$message.warning('请输入单价');
                    //         return;
                    //     }
                    //     if (!this.exchangeRate) {
                    //         this.$message.warning('请选择汇率');
                    //         return;
                    //     }
                    // }

                    item.settleName = this.settleName;
                    item.settleId = this.settleId;
                    item.bankAccount = this.bankAccount;   //银行账号
                    item.bankId = this.bankId;        //银行id
                    item.bankName = this.bankName;      //银行名称
                    item.billDate = this.billDate;
                    item.billNo = this.billNo;
                    item.officeName = this.officeName;
                    item.officeId = this.officeId;
                    item.userName = this.userName;
                    item.userId = this.userId;
                    item.crmName = this.crmName;
                    item.crmId = this.crmId;
                    item.vendorName = this.vendorName;
                    item.vendorId = this.vendorId;
                    item.projectName = this.projectName;
                    item.projectId = this.projectId;

                    item.currencyBeginAmount = this.currencyBeginAmount;   //原币金额
                    item.currencyId = this.currencyId;       //币种id
                    item.currencyName = this.currencyName;    //币种名称
                    item.exchangeRate = this.exchangeRate;    //汇率
                    item.debitAmountType = this.debitAmountType;     //借贷方向
                    item.quantityBegin = this.quantityBegin;        //数量
                    item.price = this.price;           //单价
                    item.unitId = this.unitId;          //计量单位id
                    item.unitName = this.unitName;        //计量单位名称


                    let array = [this.officeName, this.userName, this.crmName, this.projectName, this.vendorName]




                    if (this.isExchange) {//外币核算
                        let wb = [this.currencyBeginAmount, this.currencyName];
                        let wbFilter = wb.filter(r => {
                            return r;
                        })
                        array.unshift(wbFilter.join(','))
                    }

                    if (this.isQuantity) {//外币数量|| 数量
                        let sl = [this.quantityBegin];
                        let slFilter = sl.filter(r => {
                            return r;
                        })
                        array.unshift(slFilter.join(','))
                    }

                    let b = array.filter(r => {
                        return r && r.trim();
                    })

                    item.auxiliaryItem = b.join('/');
                    console.log('辅助项：', b)

                    this.reload();
                    this.auxiliaryModal = false;
                }
            });

            //计算合计
            let borrow = 0;
            let loan = 0;
            this.dataSource.forEach(item => {
                if (item.debitAmount) {
                    borrow += Number(item.debitAmount);
                }
                if (item.creditAmount) {
                    loan += Number(item.creditAmount);
                }
            });
            this.totalDebitAmount = borrow.toFixed(2);
            this.totalCreditAmount = loan.toFixed(2);
        },
        onChangeDateDay (v, s) {
            this.billDate = s;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > 9) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }
                    _this.reload();
                },
                onCancel () { },
            });
        },
        searchBackData (record) {
            console.log(record);
            if (record && record.name) {
                this.getCode();
                if (this.voucherCode != 0) {
                    this.$set(this.dataJson, 'code', record.classWord + '字第' + this.voucherCode + '号');
                    this.currentTitle = record.className;
                    this.dataJson.classWord = record.classWord;
                    this.dataJson.vclassName = record.name;
                    this.dataJson.vclassId = record.id;
                }

            } else {
                this.dataJson.vclassName = null;
                this.dataJson.vclassId = null;
            }

        },
        //获取可编辑的列名
        editColumnArray (column) {
            let editcloumn = [];
            column.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumnArraya = editcloumn;
        },
        searchGroup () {
            this.$refs.credentialsSearch.showModal();
        },
        cancel () {
            this.auxiliaryModal = false;
        },
        handleSearch (n) {
            console.log(n);
            this.$refs[`${n}`].showModal();
        },
        setValue (data) {
            console.log(data);
            if (data.codesName == 'officeName') {//部门
                this.officeName = data.name;
                this.officeId = data.id;
            }

            if (data.codesName == 'crmName') { //客户
                this.crmName = data.crmName;
                this.crmId = data.id;
            }

            if (data.codesName == 'vendorName') { //供应商
                this.vendorName = data.name;
                this.vendorId = data.id;
            }

            if (data.codesName == 'settleName') { //结算方式
                this.settleName = data.name;
                this.settleId = data.id;
            }

            if (data.codesName == 'bankAccount') { //银行账号
                this.bankAccount = data.bankAccount;
                this.bankName = data.bankName;
                this.bankId = data.id;
            }

            if (data.codesName == 'userName') { //个人
                this.userName = data.name;
                this.userId = data.id;
            }

            if (data.codesName == 'projectName') { //项目
                this.projectName = data.name;
                this.projectId = data.id;
            }

            if (data.codesName == 'exchangeRate') { //汇率
                this.exchangeRate = data.exchangeRate;
            }
        },
        //获取凭证
        getcategoryList () {
            categoryList().then(response => {
                if (response.code === 200) {
                    if (response.data.length < 1) {
                        let _this = this;
                        this.$confirm({
                            title: '提示',
                            content: '没有凭证类别，请配置！',
                            okText: '马上去配置',
                            keyboard: false,
                            closable: false,
                            onOk () {
                                console.log("准备进入地区配置页面。。。",)
                                _this.$router.push("/finance/setting/FinanceCategory");
                                // window.location.replace("/system/area/list");
                            },
                            onCancel () {

                            },
                        });
                    } else {
                        this.currentCategoryArray = response.data;
                    }
                }
            }).catch(error => { });
        },
        handlerSubmit () {
            //提交数据
            this.dataJson = this.dataSource.filter(e => { return e.accountingId });//表明细
            if (this.dataJson.length < 1) {
                this.$message.warning('请输入明细表');
                return;
            }


            //判断辅助项
            let vdetails = this.dataJson;



            for (let i = 0; i < vdetails.length; i++) {
                let item = vdetails[i];

                if (item.officeId == 0 || item.projectId == 0 || item.settleId == 0 || item.vendorId == 0 || item.userId == 0 || item.crmId == 0) {
                    if (item.auxiliaryItem == '' || !item.auxiliaryItem || item.auxiliaryItem == null) {
                        this.$message.warning(`第${i + 1}行: 辅助项必须填写完整!`);
                        return;
                    }
                }
                // if ((!item.debitAmount || item.debitAmount == 0) && (!item.creditAmount || item.creditAmount == 0)) {
                //     this.$message.warning(`第${i + 1}行: 请输入借贷金额!`);
                //     return;
                // }
            }
            let requestData = JSON.parse(JSON.stringify(this.dataJson));

            if (this.currentId) {
                requestData.id = this.currentId;
            }

            console.log('提交的数据：', requestData);
            // return;
            save(requestData).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.voucherState = 0;
                    // this.currentId = res.data;//当前数据id

                    this.getDataList();
                    // this.getDataNewPage(5);
                } else {
                    // this.$message.warning(res.message);
                }
            }).catch(error => {

            })
        },
        getDataList (t) {
            //获取列表
            if (t == 'search') {
                this.pagination.current = 1;
            }
            let data = {
                code: this.searchText,
                current: this.pagination.current,
                size: this.pagination.pageSize,
            };
            getList(data).then(res => {
                if (res.code === 200) {
                    const { records, total, current, size } = res.data;
                    this.pagination.total = res.data.total;

                    this.listDataSource = records;


                    if (records.length > 0) {
                        this.dataSource[0] = records[records.length - 1];
                    }
                    // this.newPage();
                    this.showModel = 'list';
                    this.reload();
                    this.$forceUpdate();
                }
            })
        },
        getDataNewPage (type) {
            //翻页||获取最新一条||获取当前页type==5
            let requestData = {
                actionType: type,
                currentId: this.currentId,
            }
            getPage(requestData).then(res => {
                if (res.code === 200) {
                    if (type == 1 && res.data == null) {
                        this.$message.warning('已经是首页了');
                        return;
                    }
                    if (type == 2 && res.data == null) {
                        this.$message.warning('已经是尾页了');
                        return;
                    }
                    if (res.data) {
                        this.editMask = true;
                        this.currentId = res.data.id;
                        this.voucherState = res.data.status;
                        this.currentTitle = res.data.vclassName;
                        this.invalidState = res.data.isDelete;
                        this.dataJson = res.data;
                        this.dataSource = res.data;
                        let length = res.data.length;
                        if (length < 10) {
                            for (let i = 0; i < 10 - length; i++) {
                                let array = {};
                                this.dataSource.push(array)
                            }
                        }
                        this.reload();
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            }).catch(res => {

            })
        },
        handleRemove (type) {
            //type == 0 取消作废
            //type == 1 作废
            let that = this;
            this.$confirm({
                title: type == 1 ? `是否确认删除该数据？` : `是否确认恢复该数据？`,
                content: "",
                onOk () {
                    remove({ id: that.currentId, status: type }).then(res => {
                        if (res.code == 200) {
                            if (type == 1) {
                                that.$message.success("删除成功");
                            } else {
                                that.$message.success("恢复成功");
                            }
                            that.getDataList();
                            // that.getDataNewPage(5);
                        } else {
                            that.$message.warning(res.message);
                        }
                    })
                },
                onCancel () { }
            });
        },
        //审核
        auditClick (type) {
            let requestData = {
                ids: [this.currentId],
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.voucherState = 1;
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.voucherState = 0;
                    }
                    this.getDataList();
                    this.getDataNewPage(5);
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //修改
        handleEdit () {
            this.editMask = false;
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            const { pagination } = this;

            Object.assign(this.pagination, {
                current: 1,
                pageSize: size,
            });
            this.getDataList();
        },
        syncFun () {
            //刷新
            this.ListAccount();
        }
    },

};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .credentials-wrapper {
        padding: 10px;
        height: auto;
        overflow-y: auto;
        font-size: 14px;
        min-height: 350px;
        .date-tp {
            text-align: center;
            margin-bottom: 10px;
        }
        .footer-tp {
            text-align: center;
            margin-top: 10px;
        }

        .text-name {
            // border-bottom: 2px solid rgba(0, 0, 0, 0.8);
            padding-bottom: 5px;
        }
        .subsidiary {
            border: 1px solid #cacaca;
            text-align: center;
            display: flex;
            .sub-title {
                flex: 0 0 26px;
                padding-top: 8px;
                border-right: 1px solid #cacaca;
            }
            .sub-content {
                flex: 1;
                text-align: left;
                .sub-list {
                    border-bottom: 1px solid #cacaca;
                    line-height: 32px;
                    .ant-col {
                        padding-left: 20px;
                    }
                }
                .sub-list:last-child {
                    border-bottom: none;
                }
            }
        }
        .total-box {
            border-left: 1px solid #cacaca;
            border-right: 1px solid #cacaca;
            border-bottom: 1px solid #cacaca;
            display: flex;
            line-height: 32px;
            text-align: center;
            font-size: 14px;
            .total-title {
                width: 77.2%;
                border-right: 1px solid #cacaca;
                box-sizing: content-box;
            }
            .total-borrow {
                width: 11.4%;
                border-right: 1px solid #cacaca;
            }
            .total-loan {
                width: 11.4%;
            }
        }
        label:not(.form-check-label):not(.custom-file-label) {
            font-weight: normal;
        }
        .bills-box-header {
            display: flex;
            justify-content: space-around;
            .filter {
                display: table;
                width: 246px;
                margin-bottom: 5px;
                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    line-height: 32px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
                .filter-control {
                    display: table-cell;
                    width: 100%;
                }
            }
        }
    }

    .atable-edit {
        .ant-table-tbody > tr > td {
            padding: 0px 2px !important;
        }
    }

    //辅助弹窗
    .auxiliary-wapper {
        color: #222;
        .condition {
            padding: 0 10px;
            margin-bottom: 10px;
            overflow-y: auto;
            .filter {
                display: table;
                margin-top: 10px;
                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }
                .filter-control {
                    display: table-cell;
                    width: 100%;
                }
                .ant-select-selection--single {
                    height: auto;
                }
                .ant-input-number {
                    width: auto;
                }
                .ant-input,
                .ant-input-number,
                .ant-select-selection {
                    border-radius: 0;
                    border: none;
                    border-bottom: 1px solid #ccc;
                }
                .ant-input-number,
                .ant-select-selection,
                .ant-calendar-picker,
                .ant-calendar-picker-input,
                .ant-input:focus {
                    box-shadow: none;
                }
                .ant-input-number-handler-wrap {
                    display: none;
                }
                .ant-input-group-addon {
                    border: 0px;
                }
            }
        }
    }
</style>